<script setup xmlns="http://www.w3.org/1999/html">
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import axios from "axios";
import { message } from "ant-design-vue";

const formState = reactive( {
  username : '',
  password : '',
  remember : true,
} );
const onFinish = values => {
  axios.post( '/api/user-login', values ).then( res => {
    if ( res.data.code === 200 ) {
      let resData = res.data.data;
      message.success( res.data.msg, 1, () => {
        localStorage.setItem( 'loginState', 'ok' );
        localStorage.setItem( 'token', resData.token );
        localStorage.setItem( 'userInfo', JSON.stringify( resData ) );
        window.location.href = '/';
      } );
    } else {
      message.error( res.data.msg );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '登录失败' );
  } );
};
const onFinishFailed = errorInfo => {
  console.log( 'Failed:', errorInfo );
};
const forgetPassword = () => {
  console.log( '忘记密码' );
}
</script>

<template>
  <div class="login-container">
    <a-form class="login-form" :model="formState" @finish="onFinish" @finishFailed="onFinishFailed">
      <a-form-item label="" name="username" :rules="[{ required: true, message: '请填写账户!' }]">
        <a-input v-model:value="formState.username" placeholder="请输入注册账号">
          <template #prefix>
            <UserOutlined/>
          </template>
        </a-input>
      </a-form-item>
      
      <a-form-item label="" name="password" :rules="[{ required: true, message: '请填写密码!' }]">
        <a-input-password v-model:value="formState.password" placeholder="请输入密码">
          <template #prefix>
            <LockOutlined/>
          </template>
        </a-input-password>
      </a-form-item>
      
      <a-form-item>
        <a-form-item name="remember" no-style>
          <a-checkbox v-model:checked="formState.remember">记住我</a-checkbox>
        </a-form-item>
        <a-button class="login-form-forget" @click="forgetPassword">忘记密码</a-button>
      </a-form-item>
      
      <a-form-item>
        <a-button type="primary" html-type="submit" class="login-form-button">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<style scoped>
.login-container {
  width: 420px;
  margin: 10% auto;
  border: 1px solid rgba(0, 0, 0, .1);
  border-radius: 10px;
}

.login-form {
  width: 400px;
  padding: 40px 20px 20px 20px;
  margin: 0 auto;
}

.login-form-forget {
  float: right;
}

.login-form-button {
  width: 100%;
}

</style>